package com.sh.healthtv.ui;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.sh.healthtv.R;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.PlayObserveble;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.PlayObserver;
import com.sh.healthtv.base.BaseActivity;
import com.sh.healthtv.config.Constant;
import com.sh.healthtv.webconfig.ActivityFunc;
import com.sh.healthtv.webconfig.KnowledgeJs;


public class MainActivity extends BaseActivity implements PlayObserver{
    private String TAG = "MainActivity";
    private WebView webView;

    //    private String url = "http://192.168.1.220:8020/showtv0414/%E9%99%84%E8%BF%91%E6%99%AF%E7%82%B9_%E4%BA%BA%E6%96%87%E6%99%AF%E8%A7%82.html";
    private String url1 = "file:///android_asset/healthca/healthtv/index.html";
    private String url12 = "file:///android_asset/healthca/healthca/healthTV/index.html";
    private String url13 = "http://www.jktv.tv/shportal/relax/index.html?regionCode=jktv-0-0&ch=4#/home/Player?id=b35b5ebf43ee48eda72f680ef0248f28&name=%E7%A5%9E%E5%89%AA%E8%BE%91%EF%BC%8C%E9%A9%AC%E5%86%AC%E6%A2%85%E7%89%88%E7%88%B1%E6%88%91%E4%B8%AD%E5%8D%8E&posterUrl=http%3A%2F%2F182.92.66.64%2FCMS%2F20170724%2F2017072416110428267_750_422.jpg%3Fid%3D61015%26crc%3D1848535292";
    private String url4 = "http://192.168.1.218:8085/static/healthtv/index.html#/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        Toast.makeText(this, url4, Toast.LENGTH_LONG).show();
        init();
    }

    private void init() {
        PlayObserveble.getInstance().registerObserver(this);
        webView = (WebView) findViewById(R.id.helpfeedback_wv);
        WebSettings webSettings = webView.getSettings();
       // webView.clearCache(true);
        if (Build.VERSION.SDK_INT > 17) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);//不需要请求控制直接播放媒体文件
        }
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
        webSettings.setSupportMultipleWindows(true);// 新加
        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        //使用localStorage则必须打开
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true); //兼容jw
        String dbPath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setDatabasePath(dbPath);
        webSettings.setDatabaseEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheMaxSize(1024*1024*2);//设置缓冲大小，我设的是8M
        String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        webSettings.setAppCachePath(appCacheDir);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //然后
        webView.setWebChromeClient(new MyChromeViewClient());
        ActivityFunc func = new KnowledgeJs(this);
        webView.addJavascriptInterface(func, "ActivityFunc");

        webView.setBackgroundColor(Color.parseColor("#000000"));
        webView.loadUrl(url4);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url4);
                return true;
            }
        });
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP) {

                }
                return false;
            }
        });


    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int key = event.getKeyCode();
        if (key== Constant.Control_KEYCODE_EXIT){
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.i(TAG, "goBack: " + key);
            webView.loadUrl("javascript:goBack()");
        }
        return  true;}
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void connectProgram(int type) {
        webView.loadUrl("javascript:connectProgram('" + type + "')");
        Log.i(TAG, "收藏类型"+type);
    }

    @Override
    public void programHis(int time,int type) {
        webView.loadUrl("javascript:programHis('" + time +","+ type+"')");
        Log.i(TAG, "历史记录"+time);
    }

    @Override
    protected void onDestroy() {
        PlayObserveble.getInstance().unregisterObserver(this);
        super.onDestroy();
    }
}
class MyChromeViewClient extends WebChromeClient {
    //重写这个方法就OK 了
    @Override
    public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater){
        //设置数据库存储大小
        quotaUpdater.updateQuota(estimatedSize * 1);
    }
    //扩充缓存的容量
    @Override
    public void onReachedMaxAppCacheSize(long spaceNeeded,
                                         long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
        quotaUpdater.updateQuota(spaceNeeded * 2);
    }
}